package com.zx.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.base.mybatis.ServiceImpl;
import com.zx.mapper.RoleMapper;
import com.zx.mapper.RoleRightMapper;
import com.zx.pojo.Right;
import com.zx.pojo.Role;
import com.zx.pojo.User;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色业务逻辑实现
 *
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleRightMapper roleRightMapper;

    @Resource
    private RightService rightService;

    /**
     * 获得所有角色
     */
    @Override
    public List<Role> getAllRole() {
        log.debug("------ 从数据库中获得所有角色 ------");
        return roleMapper.selectList(null);
    }

    /**
     * 分页获得角色数据
     */
    @Override
    public IPage<Role> findRoles(String roleName, Page page) {
        log.debug("------ 从数据库中获得分页角色 ------");
        return super.getPage(page, new Role(roleName));
    }

    /**
     * 保存角色以及其对应的权限关系数据
     *
     * @param role       角色信息
     * @param rightCodes 对应权限关系
     * @return
     */
    @Override
    @Transactional // 声明式事务，因为要对两张表进行操作，整体需要在一个事务中
    public boolean saveRoleAndRight(Role role, String[] rightCodes) {
        // 第一步：保存角色信息
        boolean roleok = this.saveOrUpdate(role);
        // 如果存在角色ID表示修改
        if (roleok && role.getRoleId() != null) {
            // 第二步：删除角色对应的所有权限关系（先删）
            UpdateWrapper uw = new UpdateWrapper();
            uw.eq("rf_role_id", role.getRoleId());
            roleRightMapper.delete(uw);
        }
        // 第三步：保存角色与权限对应的新关系（再加）
        boolean rolerightok = true;
        if (rightCodes != null && rightCodes.length != 0) {
            rolerightok = roleRightMapper.saveRoleRight(role, rightCodes);
        }
        return roleok && rolerightok;
    }

    /**
     * 删除角色以及对于的权限关系数据
     *
     * @param roleId 角色ID
     * @return
     */
    @Override
    @Transactional // 声明式事务，先把该角色对应的权限数据删除，再删除角色
    public boolean removeRoleAndRight(Long roleId) {
        // 第一步：先删除角色对应的权限关系数据
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq("rf_role_id", roleId);
        roleRightMapper.delete(uw);
        // 第二步：再删除角色本身信息
        boolean delok = this.removeById(roleId);
        return delok;
    }

    public void reloadFilterChainDefinitions() { // 重新加载动态权限，配置权限验证规则
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext = request.getSession().getServletContext();

            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("shiroFilterFactory");
            synchronized (shiroFilter) {
                // 获取过滤管理器
                PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                // 清空初始权限配置
                manager.getFilterChains().clear();
                // 重新加载动态权限，配置权限验证规则
                Map<String, String> chains = loadFilterChainDefinitions();
                // System.out.println("chains-------"+chains);
                for (Map.Entry<String, String> entry : chains.entrySet()) {
                    String url = entry.getKey();
                    String chainDefinition = entry.getValue().trim().replace(" ", "");
                    manager.createChain(url, chainDefinition);
                }
                System.out.println("更新权限成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> loadFilterChainDefinitions() {//加载动态权限，配置权限验证规则
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();//必须使用 LinkedHashMap(有序集合)
        //配置可以匿名访问的资源(URL)：静态资源
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/logout", "logout");//注销过滤器，自动注销
        //动态授权
        System.out.println("------ 从数据库中获得所有权限 ------");
        List<Right> rights = rightService.getAllRight(); // 获取整个系统中所有的权限信息
        for (Right right : rights) { // 动态设置受保护的每个URL的权限
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }
        //配置认证访问：其他资源(URL)必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "authc"); //必须放在过滤器链的最后面
        return filterChainDefinitionMap;
    }

    @Override
    public Role findRoleByUsers(User user) {
        return roleMapper.findRoleByUsers(user);
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return roleMapper.findRightsByRole(role);
    }
}